<template>
  <div class="p-2">
    <h1>OHLC图</h1>
    <div ref="chartRef" style="width: 100%; height: 600px"></div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import { listSymbols, listMarket } from '@/api/market/market';  // 替换原来的axios导入
const props = defineProps({
  symbol: {
    type: String,
    required: true
  }
});
const chartRef = ref<HTMLElement | null>(null);
const symbols = ref<string[]>([]); // 存储所有股票代码

const chartData = ref({
  categoryData: [] as string[],
  values: [] as number[][]
});

// 添加watch监听symbol变化
watch(
  () => props.symbol,
  (newVal) => {
    fetchData();
  }
);

// 修改后的 fetchSymbols 函数
const fetchSymbols = async () => {
  try {
    const response = await listSymbols();
    symbols.value = response.data; // 根据实际接口返回结构调整
  } catch (error) {
    console.error('Error fetching symbols:', error);
  }
};

// 数据请求和处理
const fetchData = async () => {
  try {
    const response = await listMarket({
      symbol: props.symbol, // 使用props中的symbol
      pageSize: 1000,
      pageNum: 1
    });

    // 处理数据并更新 chartData
    const data = response.rows; // 修改数据访问方式

    // 处理原始数据，转化为ECharts需要的格式
    const rawData = data.map((item: any) => [
      item.time.split(' ')[0], // 修改这里：分割日期部分
      parseFloat(item.open), // 开盘价
      parseFloat(item.preclose), // 收盘价
      parseFloat(item.low), // 最低价
      parseFloat(item.high) // 最高价
    ]);

    const { categoryData, values } = splitData(rawData);

    chartData.value = { categoryData, values };
    renderChart(); // 渲染图表
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

// 分割数据函数
function splitData(rawData: (string | number)[][]) {
  const categoryData: string[] = [];
  const values: number[][] = [];

  for (let i = 0; i < rawData.length; i++) {
    categoryData.push(rawData[i][0] as string);
    rawData[i][0] = i;
    values.push(rawData[i] as number[]);
  }

  return {
    categoryData,
    values
  };
}

// 渲染 item 函数
function renderItem(params: echarts.CustomSeriesRenderItemParams, api: echarts.CustomSeriesRenderItemAPI): echarts.CustomSeriesRenderItemReturn {
  const xValue = api.value(0);
  const openPoint = api.coord([xValue, api.value(1)]);
  const closePoint = api.coord([xValue, api.value(2)]);
  const lowPoint = api.coord([xValue, api.value(3)]);
  const highPoint = api.coord([xValue, api.value(4)]);
  const halfWidth = (api.size!([1, 0]) as number[])[0] * 0.35;
  const style = api.style({
    stroke: api.visual('color')
  });

  return {
    type: 'group',
    children: [
      {
        type: 'line',
        shape: {
          x1: lowPoint[0],
          y1: lowPoint[1],
          x2: highPoint[0],
          y2: highPoint[1]
        },
        style: style
      },
      {
        type: 'line',
        shape: {
          x1: openPoint[0],
          y1: openPoint[1],
          x2: openPoint[0] - halfWidth,
          y2: openPoint[1]
        },
        style: style
      },
      {
        type: 'line',
        shape: {
          x1: closePoint[0],
          y1: closePoint[1],
          x2: closePoint[0] + halfWidth,
          y2: closePoint[1]
        },
        style: style
      }
    ]
  };
}

// 渲染图表函数
function renderChart() {
  if (!chartRef.value) {
    return;
  }

  const myChart = echarts.init(chartRef.value, null, {
    renderer: 'svg'
  });

  const option = {
    animation: false,
    legend: {
      bottom: 10,
      left: 'center',
      data: ['K线图']
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      position: function (pos, params, el, elRect, size) {
        const obj: Record<string, number> = { top: 10 };
        obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
        return obj;
      }
    },
    axisPointer: {
      link: [{ xAxisIndex: 'all' }]
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: false
        },
        brush: {
          type: ['lineX', 'clear']
        }
      }
    },
    grid: [
      {
        left: '10%',
        right: '8%',
        bottom: 150
      }
    ],
    xAxis: [
      {
        type: 'category',
        data: chartData.value.categoryData,
        boundaryGap: false,
        axisLine: { onZero: false },
        splitLine: { show: false },
        min: 'dataMin',
        max: 'dataMax',
        axisPointer: {
          z: 100
        }
      }
    ],
    yAxis: [
      {
        scale: true,
        splitArea: {
          show: true
        }
      }
    ],
    dataZoom: [
      {
        type: 'inside',
        start: 98,
        end: 100,
        minValueSpan: 10
      },
      {
        show: true,
        type: 'slider',
        bottom: 60,
        start: 98,
        end: 100,
        minValueSpan: 10
      }
    ],
    series: [
      {
        name: 'K线图',
        type: 'custom',
        renderItem: renderItem,
        dimensions: ['-', 'open', 'close', 'lowest', 'highest'],
        encode: {
          x: 0,
          y: [1, 2, 3, 4],
          tooltip: [1, 2, 3, 4]
        },
        data: chartData.value.values
      }
    ]
  };

  myChart.setOption(option, true);

  // Handle window resize
  window.addEventListener('resize', function () {
    myChart.resize();
  });
}

onMounted(async () => {
  // 获取所有股票代码
  await fetchSymbols();
  // 请求默认股票数据
  await fetchData();
});
</script>
